How to load .env file from nodejs
AI Response
To load a .env file in a Node.js application, you can use the dotenv package. Here's a step-by-step guide:
-
Install the
dotenvpackage using npm or yarn:npm install dotenvor
yarn add dotenv -
Create a
.envfile in the root directory of your project and define your environment variables:DB_HOST=localhost DB_USER=myuser DB_PASSWORD=mypassword -
In your Node.js application entry point (typically
index.jsorapp.js), require and configuredotenvat the very beginning:require('dotenv').config(); -
Now, you can access your environment variables using
process.env:const dbHost = process.env.DB_HOST; const dbUser = process.env.DB_USER; const dbPassword = process.env.DB_PASSWORD; console.log(`Database Host: ${dbHost}`); console.log(`Database User: ${dbUser}`); console.log(`Database Password: ${dbPassword}`);
Ensure that you do not commit your .env file to version control systems, as it often contains sensitive information.
By following these steps, your Node.js application will load the environment variables from the .env file during runtime.